package com.test.gk;

import java.util.Map;
import java.util.HashMap;

public class CosineSimilarity {
    
    public static double cosineSimilarity(String text1, String text2) {
        Map<String, Integer> vector1 = getTermFrequency(text1);
        Map<String, Integer> vector2 = getTermFrequency(text2);
        
        double dotProduct = 0.0;
        double magnitude1 = 0.0;
        double magnitude2 = 0.0;
        
        for (String term : vector1.keySet()) {
            dotProduct += vector1.get(term) * vector2.getOrDefault(term, 0);
            magnitude1 += Math.pow(vector1.get(term), 2);
        }
        
        for (String term : vector2.keySet()) {
            magnitude2 += Math.pow(vector2.get(term), 2);
        }
        
        magnitude1 = Math.sqrt(magnitude1);
        magnitude2 = Math.sqrt(magnitude2);
        
        return dotProduct / (magnitude1 * magnitude2);
    }
    
    private static Map<String, Integer> getTermFrequency(String text) {
        Map<String, Integer> termFrequency = new HashMap<>();
        String[] terms = text.split(" ");
        
        for (String term : terms) {
            termFrequency.put(term, termFrequency.getOrDefault(term, 0) + 1);
        }
        
        return termFrequency;
    }

    public static void main(String[] args) {
        String text1 = "pos";
        String text2 = "PoS";
        
        double similarity = cosineSimilarity(text1, text2);
        System.out.println("Cosine similarity between the two texts: " + similarity);
    }
}